<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 连接数据库
    $link = mysqli_connect("127.0.0.1", "root", "root", "database");

    // 获取参数
    $pid = $_POST['pid'];
    $name = $_POST['name'];

    // 查询当前节点的父节点ID和左值
    $query = "SELECT pid, L FROM tree_lr WHERE id = '{$pid}'";
    $result = mysqli_query($link, $query);
    $row = mysqli_fetch_assoc($result);
    $p_id = $row['pid'];
    $l = $row['L'];

    // 将当前节点左侧的节点的左值都减2，右侧的节点的左值和右值都加2
    $query = "UPDATE tree_lr SET L = CASE WHEN L < '{$l}' THEN L - 2 ELSE L + 2 END, R = CASE WHEN R < '{$l}' THEN R - 2 ELSE R + 2 END WHERE L <= '{$l}' AND R >= '{$l}'";
    $result = mysqli_query($link, $query);

    // 插入数据，并设置左值和右值
    $query = "INSERT INTO tree_lr(name, pid, L, R, sex) VALUES ('{$name}', '{$p_id}', '".($l-1)."', '{$l}', '男')";
    $result = mysqli_query($link, $query);

    if ($result) {
        // 更新顶级节点的父节点ID为新节点的ID
        $new_id = mysqli_insert_id($link);
        $query = "UPDATE tree_lr SET pid = '{$new_id}' WHERE id = '{$pid}'";
        $result = mysqli_query($link, $query);

        if ($result) {
            // 新增成功，返回成功信息
            echo json_encode(array('success' => true));
        } else {
            // 新增失败，返回错误信息
            echo json_encode(array('success' => false, 'message' => '新增失败，请稍后再试！'));
        }
    } else {
        // 新增失败，返回错误信息
        echo json_encode(array('success' => false, 'message' => '新增失败，请稍后再试！'));
    }

    // 关闭连接
    mysqli_close($link);
}







?>